package com.cd.dao;

import com.cd.entity.Movie;
import com.cd.entity.MovieExample;
import com.cd.mapper.MovieMapper;
import com.cd.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;

/**
 * 类名：MovieDao
 * 作者：WF
 * 功能：电影数据访问对象
 */
public class MovieDao {

    // 1. 查询所有电影
    public List<Movie> findAll() throws IOException {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            MovieMapper mapper = session.getMapper(MovieMapper.class);
            return mapper.selectByExample(null);
        }
    }

    // 2. 添加电影
    public void add(Movie movie) throws IOException {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            MovieMapper mapper = session.getMapper(MovieMapper.class);
            mapper.insert(movie);
        }
    }

    // 3. 修改电影
    public void update(Movie movie) throws IOException {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            MovieMapper mapper = session.getMapper(MovieMapper.class);
            mapper.updateByPrimaryKeySelective(movie);
        }
    }

    // 4. 删除电影
    public void delete(Integer movieId) throws IOException {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            MovieMapper mapper = session.getMapper(MovieMapper.class);
            mapper.deleteByPrimaryKey(movieId);
        }
    }

    // 5. 根据条件查询电影
    public List<Movie> search(MovieExample example) throws IOException {
        try (SqlSession session = MybatisUtil.getSqlSession(true)) {
            MovieMapper mapper = session.getMapper(MovieMapper.class);
            return mapper.selectByExample(example);
        }
    }
}